package com.whfc.ms.api.cfg.service.factory;

import com.alibaba.fastjson.JSON;
import com.whfc.base.dto.AppWarnFreqConfigDTO;
import com.whfc.base.enums.AppModuleType;
import com.whfc.base.service.WarnConfigService;
import com.whfc.common.exception.BizException;
import com.whfc.common.result.ResultEnum;
import com.whfc.mach.dto.MachValidFenceDTO;
import com.whfc.mach.dto.strategy.MachStrategyDTO;
import com.whfc.mach.service.AppMachConfigService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * @author qzexing
 * @version 1.0
 * @date 2021-07-30 15:28
 */
@Service(ConfigCenterServiceConstant.MACH_SERVICE)
public class ConfigCenterServiceMachImpl implements ConfigCenterService {

    @DubboReference(interfaceClass = WarnConfigService.class, version = "1.0.0")
    private WarnConfigService warnConfigService;

    @DubboReference(interfaceClass = AppMachConfigService.class, version = "1.0.0")
    private AppMachConfigService appMachConfigService;

    @Override
    public List getConfigList(Integer deptId, String module) {
        if (ConfigCenterModuleConstant.MACH_FREQ.equals(module)) {
            return warnConfigService.getFreqConfigList(deptId, AppModuleType.MACH);
        } else if (ConfigCenterModuleConstant.MACH_STRATEGY.equals(module)) {
            return appMachConfigService.getStrategyConfig(deptId);
        } else if (ConfigCenterModuleConstant.MACH_FENCE.equals(module)) {
            return appMachConfigService.getMachValidFenceList(deptId);
        }
        return Collections.emptyList();
    }

    @Override
    public void setConfig(Integer deptId, String module, String dataStr) {
        if (ConfigCenterModuleConstant.MACH_FREQ.equals(module)) {
            List<AppWarnFreqConfigDTO> freqConfigList = JSON.parseArray(dataStr, AppWarnFreqConfigDTO.class);
            if (freqConfigList == null) {
                throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "参数类型错误.");
            }
            warnConfigService.freqConfigure(deptId, AppModuleType.MACH, freqConfigList);
        } else if (ConfigCenterModuleConstant.MACH_STRATEGY.equals(module)) {
            List<MachStrategyDTO> strategyList = JSON.parseArray(dataStr, MachStrategyDTO.class);
            if (strategyList == null) {
                throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "参数类型错误.");
            }
            appMachConfigService.strategyConfigure(deptId, strategyList);
        } else if (ConfigCenterModuleConstant.MACH_FENCE.equals(module)) {
            List<MachValidFenceDTO> validFenceList = JSON.parseArray(dataStr, MachValidFenceDTO.class);
            if (validFenceList == null) {
                throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "参数类型错误.");
            }
            appMachConfigService.setMachValidFence(deptId, validFenceList);
        }
    }

}
